<template>
  <div class="article-page">
    <div class="nav">
      <div class="nav-row">
        <el-tabs v-model="activeCategory" @tab-change="onCategoryChange" class="nav-tabs">
          <el-tab-pane v-for="c in categories" :key="c.key" :label="c.label" :name="c.key" />
        </el-tabs>
        <div class="nav-actions">
          <el-button type="primary" @click="toPublish">发表文章</el-button>
        </div>
      </div>
    </div>

    <div class="list">
      <ArticleCard v-for="it in rows" :key="it.id" :article="it" @click="toDetail(it)" />
      <div v-if="!loading && rows.length === 0" class="empty">暂无文章</div>
    </div>

    <div class="pager" v-if="total > pageSize">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="(p:number)=>{ page=p; fetchList() }"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { fetchArticles } from '@/api/article/article'
import ArticleCard from '@/components/article/ArticleCard.vue'
import type { ArticleSummary } from '@/types/Article'
const categories = [
  { key: 'RECOMMEND', label: '推荐' },
  { key: '心理咨询', label: '心理咨询' },
  { key: '缓解焦虑', label: '缓解焦虑' },
  { key: '情感危机', label: '情感危机' },
  { key: '改善人际', label: '改善人际' },
  { key: '个人成长', label: '个人成长' },
]
const activeCategory = ref('RECOMMEND')

const loading = ref(false)
const rows = ref<ArticleSummary[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = 10

const router = useRouter()

async function fetchList() {
  loading.value = true
  try {
    const { list, total: t } = await fetchArticles({ page: page.value, size: pageSize, category: activeCategory.value })
    rows.value = list
    total.value = t
  } finally {
    loading.value = false
  }
}

function onCategoryChange() {
  page.value = 1
  fetchList()
}

function toDetail(item: ArticleSummary) {
  // 预留详情路由跳转（待后端接口与页面就绪）
  // router.push({ name: 'article-detail', params: { id: item.id } })
}

function toPublish() {
  router.push({ name: 'article-create' })
}

watch(() => activeCategory.value, fetchList, { immediate: true })
</script>
<style scoped>
.article-page { max-width: 960px; margin: 0 auto; padding: 16px; }
.nav { position: sticky; top: 0; background: #fff; z-index: 1; padding-top: 4px; }
.nav-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.nav-tabs { flex: 1; }
.nav-actions { flex-shrink: 0; }
.list { background: #fff; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); overflow: hidden; }
.empty { padding: 24px; color: #64748b; text-align: center; }
.pager { margin-top: 12px; text-align: right; }
</style>
